﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextCodec>
#include <QMessageBox>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    ui->setupUi(this);
    ui->tabWidget->setCurrentIndex(0);
    ui->tabWidget->setEnabled(false);

    master = new SerialMaster(this);

    connect(master, SIGNAL(connectionChanged(bool)), this, SLOT(onSerialConntionChanged(bool)));

    updateAvailablePortList();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::writeLogMsg(QString msg)
{
    int i = ui->tabWidget->currentIndex();
//    msg.append("\r\n");
    if(i == 0)
    {
        ui->logMsg1->append(msg);
    }
    else
    {
        ui->logMsg2->append(msg);
    }
}

void MainWindow::writeLogMsg(const char *str)
{
    writeLogMsg(QString(str));
}

void MainWindow::updateAvailablePortList()
{
    int i;

    qDebug() << "刷新串口列表";
    infos = master->availablePorts();
    for(i = ui->portSelectBox->count(); i >= 0; i--)
    {
        ui->portSelectBox->removeItem(i);
    }

    for(i = 0; i < infos.count(); i++)
    {
        const SerialMaster::Info info = infos.at(i);
        QString str = info.name;
        str.append(info.isBusy ? " - 占用" : " - 空闲");

        ui->portSelectBox->addItem(str);
    }
}

void MainWindow::on_checkBoxSerialAuto_stateChanged(int arg1)
{

}

void MainWindow::on_checkBoxLockNumAuto_stateChanged(int arg1)
{

}

void MainWindow::on_connectButton_clicked()
{
    QString portName;
    int i;

    if(master->isSerialConnected())
    {
        master->serialDisconnect();
    }
    else
    {
        i = ui->portSelectBox->currentIndex();
        if(master->serialConnect(infos.at(i).name) != SerialMaster::State_Success)
        {
            QString title = "串口打开失败";
            writeLogMsg(title);
            QMessageBox::warning(this,
                                 title,
                                 QString("串口不存在或被其他应用程序占用！"));
        }
    }
}

void MainWindow::onSerialConntionChanged(bool isConnected)
{
    QString msg = "串口: ";
    msg.append(master->serial->portName());
    msg.append(isConnected ? "已连接" : "已断开");
    writeLogMsg(msg);
    qDebug() << msg.toStdString().c_str();

    ui->portSelectBox->setEnabled(! isConnected);
    ui->reloadButton->setEnabled(! isConnected);
    ui->connectButton->setText(QString(isConnected ? "断开" : "连接"));
    ui->tabWidget->setEnabled(isConnected);
}

void MainWindow::on_reloadButton_clicked()
{
    updateAvailablePortList();
}
